﻿Public Class frm_Recibo
    Enum estado
        insertar
        modificar
    End Enum
    Dim _accion As estado
    Dim _acceso As New AccesoBD
    Dim _legajo, _formaPago, _idRecibo As Integer
    Dim _subtotal As Double
    Dim _selecciono As Boolean = False

#Region "Eventos"
    Private Sub frm_Recibo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.txtTotal.Enabled = False
        Me.txtFecha.Enabled = False
        Me.txtFecha.Text = Date.Now
        Me.grupoAlumno.Enabled = False
        Me.grupoFormaPago.Enabled = False
        Me.btn_grabar.Enabled = False
        'Me.cargoCombos()
        'Me.cmbNombreFPago.Enabled = False
        'Me.txtNumero.Enabled = False        

    End Sub

    Private Sub cmbAlumno_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbAlumno.SelectionChangeCommitted
        _legajo = Me.cmbAlumno.SelectedValue
        Dim con As String
        Dim tabla As New DataTable
        con = "select a.nombre, a.apellido, cu.idCurso, t.nombre, c.nroCuota, c.fechaVencimiento, total="
        con &= " case 	when c.fechaVencimiento < GETDATE() then (((c.precio*c.interes)/100)+c.precio)"
        con &= " else c.precio"
        con &= " End"
        con &= " from CuotasXAlumno c, Alumnos a, TipoCurso t, Cursos cu "
        con &= " where(c.legajoAlumno = a.legajoAlumno And cu.idCurso = c.idCurso And cu.fechaInicio = c.fechaInicio And cu.idTipoCurso = t.idTipoCurso And c.pagada = 0)"
        con &= " and c.legajoAlumno = " & _legajo
        tabla = _acceso.ejecutaSQL(con)
        Me.grillaAlumno.Rows.Clear()
        Dim c As Integer
        For c = 0 To tabla.Rows.Count - 1
            Me.grillaAlumno.Rows.Add(tabla.Rows(c)(0), tabla.Rows(c)(1), tabla.Rows(c)(2), tabla.Rows(c)(3), tabla.Rows(c)(4), tabla.Rows(c)(5), tabla.Rows(c)(6))
        Next
    End Sub

    Private Sub cmbFormaPago_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbFormaPago.SelectionChangeCommitted
        _formaPago = Me.cmbFormaPago.SelectedValue

        Select Case _formaPago
            Case 1
                Me.cmbNombreFPago.SelectedIndex = -1
                Me.txtNumero.Text = ""
                Me.cmbNombreFPago.Enabled = False
                Me.txtNumero.Enabled = False
            Case 2
                _acceso.load_combo(Me.cmbNombreFPago, _acceso.devuelveTabla("Tarjetas"), "idTarjeta", "nombre")
                Me.cmbNombreFPago.Enabled = True
                Me.txtNumero.Enabled = True
            Case 3
                _acceso.load_combo(Me.cmbNombreFPago, _acceso.devuelveTabla("Bancos"), "idBanco", "nombre")
                Me.cmbNombreFPago.Enabled = True
                Me.txtNumero.Enabled = True
        End Select
    End Sub

    Private Sub grillaAlumno_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grillaAlumno.CellClick
        '
        Me.grillaAlumno.Rows(e.RowIndex).Cells("col_chk").Value = Not Me.grillaAlumno.Rows(e.RowIndex).Cells("col_chk").Value

        If Me.grillaAlumno.Rows(e.RowIndex).Cells("col_chk").Value = True Then
            _subtotal = _subtotal + Me.grillaAlumno.CurrentRow.Cells("col_subtotal").Value
            Me.txtTotal.Text = _subtotal
            Me.txtImporte.Text = _subtotal            
        Else
            _subtotal = _subtotal - Me.grillaAlumno.CurrentRow.Cells("col_subtotal").Value
            Me.txtTotal.Text = _subtotal
            Me.txtImporte.Text = _subtotal            
        End If

    End Sub

    Private Sub txtNumero_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNumero.KeyPress, txtImporte.KeyPress, txtLegajoBusca.KeyPress
        If e.KeyChar = vbBack Then
            Exit Sub
        End If

        If Char.IsLetter(e.KeyChar) Then
            MessageBox.Show("Solo se permiten numeros", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            e.KeyChar = ""
        End If
    End Sub

    Private Sub frm_Recibo_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If MessageBox.Show("Esta seguro que desea salir?", "Salir", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            e.Cancel = True
        Else
            e.Cancel = False
        End If
    End Sub
#End Region

    Private Sub numeroRecibo()
        Dim consulta As String
        Dim tabla As New DataTable

        consulta = "select MAX(nroRecibo)+1 from Recibos"
        tabla = _acceso.ejecutaSQL(consulta)

        If IsDBNull(tabla.Rows(0)(0)) Then
            Me.lblNumRecibo.Text = 1000
        Else
            Me.lblNumRecibo.Text = tabla.Rows(0)(0)
        End If
        _idRecibo = lblNumRecibo.Text
    End Sub

    Private Sub cargoCombos()
        _acceso.load_combo(Me.cmbFormaPago, _acceso.devuelveTabla("FormasDePago"), "idFormaPago", "descripcion")
    End Sub

    Private Sub buscarPorLegajo(ByVal legajo As Integer)
        Dim con As String
        Dim tabla As New DataTable

        con = "select legajoAlumno, apellido + ', ' + nombre as nombre from Alumnos where legajoAlumno = " & legajo
        tabla = _acceso.ejecutaSQL(con)
        If tabla.Rows.Count = 0 Then
            MessageBox.Show("No existe el alumno ingresado", "Buscar", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtLegajoBusca.Focus()
            Exit Sub
        Else
            _acceso.load_combo(Me.cmbAlumno, tabla, "legajoAlumno", "nombre")
        End If
    End Sub

    Private Sub buscaPorNombre(ByVal nombre As String)
        Dim con As String
        Dim tabla As New DataTable

        con = "select legajoAlumno, apellido + ', ' + nombre as nombre from Alumnos where nombre like '" & nombre & "'" & " or apellido like '" & nombre & "'"
        tabla = _acceso.ejecutaSQL(con)
        If tabla.Rows.Count = 0 Then
            MessageBox.Show("No existe el alumno ingresado", "Buscar", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtNombreBusca.Focus()
            Exit Sub
        Else
            _acceso.load_combo(Me.cmbAlumno, tabla, "legajoAlumno", "nombre")
        End If
    End Sub

    Private Sub setRestoValorCuota()
        Dim cuota As Double
        Dim c As Integer
        For c = 0 To Me.grillaFormaPago.Rows.Count - 1
            cuota = cuota + Me.grillaFormaPago.CurrentRow.Cells(3).Value
        Next

        _subtotal = _subtotal - cuota
        If _subtotal > 0 Then
            Me.txtImporte.Text = _subtotal
        End If
    End Sub

    Private Function validarFormaPago() As Boolean
        If Me.cmbFormaPago.SelectedIndex = -1 Then
            MessageBox.Show("Debe seleccionar una forma de pago", "Forma Pago", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.cmbFormaPago.Focus()
            Return False
            Exit Function
        End If

        Dim c As Integer
        For c = 0 To Me.grillaFormaPago.Rows.Count - 1
            If Me.grillaFormaPago.CurrentRow.Cells(0).Value = "Contado" Then
                If Me.cmbFormaPago.Text = "Contado" Then
                    MessageBox.Show("Solo se permite una forma de pago de contado", "Forma Pago", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Return False
                    Exit Function
                End If
            End If
        Next

        If cmbFormaPago.SelectedValue = 2 And Me.cmbNombreFPago.SelectedIndex = -1 Then
            MessageBox.Show("Debe seleccionar una tarjeta", "Tarjeta", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.cmbNombreFPago.Focus()
            Return False
            Exit Function
        End If

        If cmbFormaPago.SelectedValue = 3 And Me.cmbNombreFPago.SelectedIndex = -1 Then
            MessageBox.Show("Debe seleccionar un banco", "Banco", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.cmbNombreFPago.Focus()
            Return False
            Exit Function
        End If

        If Me.cmbNombreFPago.SelectedIndex <> -1 And Me.txtNumero.Text = "" Then
            MessageBox.Show("Debe indicar un numero", "Numero", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtNumero.Focus()
            Return False
            Exit Function
        End If

        If String.IsNullOrWhiteSpace(Me.txtImporte.Text) Then
            MessageBox.Show("Debe indicar un importe", "Importe", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtImporte.Focus()
            Return False
            Exit Function
        End If

        If Convert.ToDouble(Me.txtImporte.Text) > _subtotal Then
            MessageBox.Show("El importe a pagar no puede ser mayor al total", "Importe", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtImporte.Focus()
            Return False
            Exit Function
        End If

        If grillaFormaPago.Rows.Count = 2 Then
            MessageBox.Show("Solo se permiten dos formas de pago", "Forma Pago", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return False
            Exit Function
        End If

        If Me.grillaFormaPago.Rows.Count = 1 And (Me._subtotal - Me.txtImporte.Text) <> 0 Then
            MessageBox.Show("La suma de las cuotas no puede ser distinto al Total", "Forma Pago", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtImporte.Focus()
            Return False
            Exit Function
        End If

        For c = 0 To Me.grillaFormaPago.Rows.Count - 1
            If Me.grillaFormaPago.Rows.Count = 1 And Me._subtotal = 0 Then
                MessageBox.Show("Ya se abono el Total", "Forma Pago", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return False
                Exit Function
            End If
        Next
        Return True
    End Function

    Private Sub limpiarFormaPago()
        Dim control As Object
        For Each control In Me.grupoFormaPago.Controls
            If control.GetType Is GetType(System.Windows.Forms.TextBox) Then
                control.Clear()
            End If
            If control.GetType Is GetType(System.Windows.Forms.ComboBox) Then
                control.SelectedValue = -1
            End If
        Next
    End Sub

    Private Sub insertarRecibo()
        Dim consulta As String

        consulta = "insert into Recibos(nroRecibo,legajoAlumno,fecha,total) values (" & Me.lblNumRecibo.Text & ", " & _legajo & ", '" & Me.txtFecha.Text & "', " & Me.txtTotal.Text & ")"
        _acceso.ejecutarTransaccion(consulta)
    End Sub

    Private Sub insertarDetalleRecibo()
        Dim consulta, aux, aux2 As String
        Dim dt As New DataTable

        For Each row As DataGridViewRow In Me.grillaAlumno.Rows
            If row.Cells("col_chk").Value = True Then
                aux = "select fechaInicio from Cuotas where idCurso = " & row.Cells("col_id_curso").Value & " and nroCuota = " & row.Cells("col_cuota").Value
                dt = _acceso.ejecutaSQL(aux)
                Dim fechaInicio As DateTime = dt.Rows(0)(0)

                aux2 = "update CuotasXAlumno set pagada = 1 where legajoAlumno = " & _legajo & " and idCurso = " & row.Cells("col_id_curso").Value & " and nroCuota = " & row.Cells("col_cuota").Value
                _acceso.ejecutarTransaccion(aux2)

                consulta = "insert into DetalleRecibo values (" & _idRecibo
                consulta &= ", " & row.Cells("col_cuota").Value & ", "
                consulta &= row.Cells("col_id_curso").Value & ", '"
                consulta &= fechaInicio & "')"
                _acceso.ejecutarTransaccion(consulta)
            End If
        Next
    End Sub

    Private Sub insertarPagosRecibo()
        Dim consulta As String

        For Each row As DataGridViewRow In Me.grillaFormaPago.Rows
            consulta = "insert into PagosRecibo(nroRecibo,idFormaPago,cantAbonada) values (" & Me.lblNumRecibo.Text & ", " & row.Cells(4).Value & ", " & row.Cells(3).Value & ")"
            _acceso.ejecutarTransaccion(consulta)
        Next
    End Sub

    Private Sub limipiarCampos()
        Dim control As Object
        For Each control In Me.grupoAlumno.Controls
            If control.GetType Is GetType(System.Windows.Forms.TextBox) Then
                control.Clear()
            End If
            If control.GetType Is GetType(System.Windows.Forms.ComboBox) Then
                control.SelectedValue = -1
            End If
        Next
        For Each control In Me.Controls
            If control.GetType Is GetType(System.Windows.Forms.TextBox) Then
                control.Clear()
            End If
        Next

        Me.grillaAlumno.Rows.Clear()
        Me.grillaFormaPago.Rows.Clear()
    End Sub

    Private Function validar() As Boolean
        If _legajo = 0 Then
            MessageBox.Show("Debe seleccionar un alumno", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Me.txtLegajoBusca.Focus()
            Return False
            Exit Function
        End If

        For Each row As DataGridViewRow In Me.grillaAlumno.Rows
            If row.Cells("col_chk").Value = True Then
                _selecciono = True
                Exit For
            End If
        Next
        If _selecciono = False Then
            MessageBox.Show("Debe seleciconar al menos una cuota", "Seleccionar cuota", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        End If

        If (_selecciono = True) And (_subtotal > 0) And (Me.grillaFormaPago.Rows.Count = 0) Then
            MessageBox.Show("Debe indicar una forma de pago", "Forma Pago", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Me.cmbFormaPago.Focus()
            Return False
            Exit Function
        End If

        Return True
    End Function


#Region "Botones"
    Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
        If validarFormaPago() Then
            Me.grillaFormaPago.Rows.Add(Me.cmbFormaPago.Text, Me.cmbNombreFPago.Text, Me.txtNumero.Text, Me.txtImporte.Text, Me.cmbFormaPago.SelectedValue)
            Me.limpiarFormaPago()
            setRestoValorCuota()
        End If
    End Sub

    Private Sub btn_salir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_salir.Click
        Me.Close()
    End Sub

    Private Sub btn_nuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_nuevo.Click
        _accion = estado.insertar
        Me.numeroRecibo()
        Me.grupoAlumno.Enabled = True
        Me.grupoFormaPago.Enabled = True
        Me.cargoCombos()
        Me.btn_grabar.Enabled = True
        Me.txtLegajoBusca.Focus()
    End Sub

    Private Sub btn_grabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_grabar.Click
        If validar() Then
            If _accion = estado.insertar Then
                _acceso.iniciarTransaccion()
                Me.insertarRecibo()
                Me.insertarDetalleRecibo()
                Me.insertarPagosRecibo()
                _acceso.finalizarTransaccion()
            End If
            MessageBox.Show("Se grabo correctamente!", "Grabar", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.limipiarCampos()
            Me.grupoAlumno.Enabled = False
            Me.grupoFormaPago.Enabled = False
            Me.btn_grabar.Enabled = False
        End If
        
    End Sub

    Private Sub btnBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscar.Click
        If Not String.IsNullOrWhiteSpace(Me.txtLegajoBusca.Text) Then
            Me.buscarPorLegajo(Me.txtLegajoBusca.Text)
        End If
        If Not String.IsNullOrWhiteSpace(Me.txtNombreBusca.Text) Then
            Me.buscaPorNombre(Me.txtNombreBusca.Text)
        End If
    End Sub
#End Region

    Private Sub btn_cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancelar.Click
        Me.limipiarCampos()
        Me.grupoAlumno.Enabled = False
        Me.grillaAlumno.Rows.Clear()
        Me.grillaFormaPago.Rows.Clear()
        Me.limpiarFormaPago()
        Me.grupoFormaPago.Enabled = False
        Me.btn_grabar.Enabled = False
    End Sub

    Private Sub btn_refrescar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_refrescar.Click
        Me.limipiarCampos()
        'Me.cmbAlumno.Items.Clear()
        Me.grillaAlumno.Rows.Clear()
        Me.limpiarFormaPago()
        Me.grillaFormaPago.Rows.Clear()
    End Sub
End Class